//
//  RelesedGoodsViewController.m
//  PalmChangtu
//
//  Created by shaorui on 15/6/17.
//  Copyright (c) 2015年 PalmChangtu. All rights reserved.
//

#import "RelesedGoodsViewController.h"
#import "ReleseGoodsViewController.h"
#import "RelesedGoodsCell.h"
#import "ShareUserModel.h"

#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"
#import "TestCollectionViewController.h"
#import "UIImageView+AFNetworking.h"
#import "UIImageView+WebCache.h"

#import "all_commodity_TypeModel.h"
#import "localJSONModel.h"
#import "MTLJSONAdapter.h"
#import "GoodsInfoModel.h"
#import "RelesedGoodsCell.h"
#import "RelesedGoodsModel.h"
#import "RelesedGoodsCollCell.h"
@interface RelesedGoodsViewController ()
{

    BOOL isRequest ;

    NSUInteger currentNum;
    NSInteger   pageNum;

}

@end

@implementation RelesedGoodsViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
-(void)viewDidAppear:(BOOL)animated
{


    if (isRequest) {
        isRequest = YES;
        [self  RelesedGoodsRequest];
    }
}
-(void)viewDidDisappear:(BOOL)animated
{
    currentNum =  0;
    pageNum = 0;


}
- (void)viewDidLoad {
    [super viewDidLoad];
    isRequest = YES;
    currentNum =  0;
    pageNum = 10;
    [_v_Top.lalTitel setText:@"已发布的商品"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
        //    TableView
        //user nib


    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.CollectionView.frame.size.width/2,200);//定义大小，也可以在代理里面定义
    flowLayout.minimumInteritemSpacing=0.0f;//左右间隔
    flowLayout.minimumLineSpacing=0.0f;

    //      设置横向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset=UIEdgeInsetsMake(0, 0, 0, 0);

    self.CollectionView.collectionViewLayout = flowLayout;
    self.CollectionView.delegate = self;
    self.CollectionView.dataSource = self;
    UINib *nibCellCollection = [UINib nibWithNibName:NSStringFromClass([RelesedGoodsCollCell class]) bundle:nil];

    [self.CollectionView registerNib:nibCellCollection forCellWithReuseIdentifier:[NSString stringWithFormat:@"%@",[RelesedGoodsCollCell class]]];



    
    _arrData = [[NSMutableArray alloc] init];
    

    // Do any additional setup after loading the view from its nib.
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{

    return 1;



}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return [_arrData count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{


    //
    static NSString *cellIdent = @"RelesedGoodsCollCell";
    RelesedGoodsCollCell * cell;
    cell = (RelesedGoodsCollCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdent forIndexPath:indexPath];

    if (_arrData.count !=0) {
        RelesedGoodsModel * model = [_arrData objectAtIndex:indexPath.row];

        cell.labName.text = model.name;
        cell.labPrice.text = [NSString stringWithFormat:@"¥%@",model.price];
        [cell.imageVie sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HostImage,model.photoUrl]]];
        [cell.btnEdit removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
        [cell.btnEdit addTarget:self action:@selector(btnEditAction:) forControlEvents:UIControlEventTouchUpInside];


        cell.btnEdit.tag  = indexPath.row;

    }





    return cell;



}

-(void)btnEditAction:(UIButton *)editAction
{


    RelesedGoodsModel * mode  = [_arrData objectAtIndex:editAction.tag];

    ReleseGoodsViewController * ReleseGoods = [[ReleseGoodsViewController alloc] initWithNibName:@"ReleseGoodsViewController" bundle:nil];

    ReleseGoods.strEditTemp = @"RelesedGoodsViewController";
    ReleseGoods.modelTemp = mode;
    [self.navigationController pushViewController:ReleseGoods animated:YES];
}

#pragma mark - UICollectionViewDelegate

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{


    //    NSString * str =[NSString stringWithFormat:@"%@",[_arrayMenuData objectAtIndex:indexPath.row]];
    //    UIAlertView * sss = [[UIAlertView alloc] initWithTitle:@"你点的是"message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"CANCLE",@"OK", nil];
    //
    //    [sss show];
    //

    //    MenuCell * cell = (MenuCell*)[collectionView cellForItemAtIndexPath:indexPath];
    
}


#pragma mark - network request publish_commodityAction

-(void)RelesedGoodsRequest
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,get_seller_commoditysAction];


    ShareUserModel * shareUser  = [ShareUserModel shareUserModel];

    NSDictionary *params = @{

                             @"currentNum":[NSNumber numberWithInteger:currentNum],
                             @"pageNum":[NSNumber numberWithInteger:pageNum],
                             @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId],
                             @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id]

                             };





    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self RelesedGoodsSuccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)RelesedGoodsSuccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue ==1)
    {


        NSArray *arrBussi = [dicRespon objectForKey:@"arr"];
    if (arrBussi.count==0) {
        
        currentNum  = 0 ;
        
        
        pageNum = 10 ;
        
        
    }
        if (arrBussi && [arrBussi isKindOfClass:[arrBussi class]])
        {
        [_arrData removeAllObjects];

            for (NSDictionary *dicTmp in arrBussi)
            {
                NSError *error = nil;
                RelesedGoodsModel *modelTmp =
                [MTLJSONAdapter modelOfClass:[RelesedGoodsModel class] fromJSONDictionary:dicTmp error:&error];
                if(error == nil)
                {
                    [_arrData addObject:modelTmp];
                }
            }

        }



        [self.CollectionView reloadData];

        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
